import 'dart:convert';

import 'package:flutter/foundation.dart';

import '../entity/app_version.dart';
import '../entity/artwork_model.dart';
import '../entity/palette_model.dart';
import '../utils/config_loader/global_config_loader.dart';
import '../utils/db_utils.dart';

/// 设置service
class GlobalConfigService {
  /// 查询配置项
  static Future<String> _queryConfigByKey(String key) async {
    final db = await DbUtils.database;
    return await db
        .query('setting', where: 'key = ?', whereArgs: [key], limit: 1)
        .then((value) {
          if (value.isNotEmpty) {
            return value.first['value'] as String;
          }
          return '';
        });
  }

  /// 更新配置项
  static _updateConfigByKey(String key, String value) async {
    // 不允许存空value
    if (value.isEmpty) {
      return;
    }
    var val = await _queryConfigByKey(key);
    final db = await DbUtils.database;
    if (val.isEmpty) {
      await db.insert('setting', {'key': key, 'value': value});
    } else {
      await db.update(
        'setting',
        {'value': value},
        where: 'key = ?',
        whereArgs: [key],
      );
    }
  }

  /// 获取画布配置
  static Future<CanvasConfig> getCanvasConfig() async {
    var value = await _queryConfigByKey('canvasConfig');
    if (kDebugMode) {
      print('获取画布配置: $value');
    }
    return GlobalConfigLoader.loadCanvasConfig(value);
  }

  /// 设置画布配置
  static setCanvasConfig(CanvasConfig value) {
    if (kDebugMode) {
      print('设置画布配置: ${value.toJson()}');
    }
    _updateConfigByKey(
      'canvasConfig',
      jsonEncode({
        'value': value.toJson(),
        'version': AppVersion.v0_0_1.version,
      }),
    );
  }

  /// 获取调色板配置
  static Future<List<PaletteModel>> getPaletteSetting() async {
    var value = await _queryConfigByKey('paletteSetting');
    if (kDebugMode) {
      print('获取调色板配置: $value');
    }
    return GlobalConfigLoader.loadPaletteSetting(value);
  }

  /// 设置调色板配置
  static setPaletteSetting(PaletteModel value) {
    if (kDebugMode) {
      print('设置调色板配置: ${value.toJson()}');
    }
    _updateConfigByKey(
      'paletteSetting',
      jsonEncode({
        'value': value.toJson(),
        'version': AppVersion.v0_0_1.version,
      }),
    );
  }
}
